#include <defs.h>
#include <pq.h>
#include <td.h>

void PqInit( pq *queue ) {
  queue->head = NULL;
  queue->size = 0;
}

int PqEmpty( pq *queue ) {
  return queue->head == NULL;
}

int PqSize( pq *queue ) {
  return queue->size;
}

td* PqFront( pq *queue ) {
  return queue->head;
}

td* PqPopFront( pq *queue ) {
	td* front = queue->head;
	PqErase(queue, front);
  return front;
}

void PqPushBack( pq *queue, td *task ) {
  if ( PqEmpty( queue ) ) {
    queue->head = task->next = task->prev = task;
  } else {
    task->prev = queue->head->prev;
    queue->head->prev->next = task;
    task->next = queue->head;
    queue->head->prev = task;
  }
  queue->size++;
}

int PqErase( pq *queue, td *task ) {
  if ( PqEmpty( queue ) ) return 0;
  if ( task == task->next ) {
    // only one element in queue
    queue->head = task->next = task->prev = NULL;
  } else {
    if ( queue->head == task ) {
      queue->head = task->next;
    }
    task->next->prev = task->prev;
    task->prev->next = task->next;
    task->next = task->prev = NULL;
  }
  queue->size--;
  return 1;
}
